package com.xy_pro.xymanager.helper;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class MpWeChatUtils {

    @Value("${mp_wechat.app-id}")
    private String appId;

    @Value("${mp_wechat.app-secret}")
    private String appSecret;

    private RestTemplate restTemplate = new RestTemplate();

    // 获取access_token（需缓存，避免频繁请求）
    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token" +
                "?grant_type=client_credential" +
                "&appid=" + appId +
                "&secret=" + appSecret;

        try {
            String result = restTemplate.getForObject(url, String.class);
            JSONObject json = JSONObject.parseObject(result);

            if (json.containsKey("access_token")) {
                return json.getString("access_token");
            } else {
                log.error("获取access_token失败: {}", result);
                return null;
            }
        } catch (Exception e) {
            log.error("获取access_token异常", e);
            return null;
        }
    }

    // 发送模板消息
    public boolean sendTemplateMessage(String openId, String templateId, String url, JSONObject data) {
        String accessToken = getAccessToken();
        if (accessToken == null) {
            return false;
        }

        String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

        JSONObject request = new JSONObject();
        request.put("touser", openId);
        request.put("template_id", templateId);
        request.put("url", url);
        request.put("data", data);

        try {
            String result = restTemplate.postForObject(sendUrl, request, String.class);
            JSONObject response = JSONObject.parseObject(result);

            if (response.getIntValue("errcode") == 0) {
                return true;
            } else {
                log.error("发送模板消息失败: {}", result);
                return false;
            }
        } catch (Exception e) {
            log.error("发送模板消息异常", e);
            return false;
        }
    }
}
